// 定义路由
import Vue from 'vue'
import VueRouter from 'vue-router'
// 引入组件配置路由
/* import Home from '@/views/Home'
import Car from '@/views/Car'
import Topic from '@/views/Topic'
import Category from '@/views/Category'
import User from '@/views/User'
import Search from '@/views/Search'
import ProductDetail from '@/views/ProductDetail' */

Vue.use(VueRouter)
const routes = [
  {
    path:'/',
    redirect:'/home'
  },
  {
    path:'/home',
    component:()=>import ('@/views/Home'),
    meta: { 
      isshowtanbar: true ,
    },
    children:[
      {
        path:'search',
        component:()=>import ('@/views/Search'),
        meta: { 
        isshowtanbar: false ,
        },
      },
      {
        path:'channel',
        component:()=>import ('@/components/Channel'),
        meta: { 
          isshowtanbar: false ,
        },
      }
    ]
  },
  {
    path:'/car',
    component:()=>import ('@/views/Car'),
    meta: { 
      isshowtanbar: true 
    },
  },
  {
    path:'/topic',
    component:()=>import ('@/views/Topic'),
    meta: { 
      isshowtanbar: true 
    },
  },
  {
    path:'/category',
    component:()=>import ('@/views/Category'),
    meta: { 
      isshowtanbar: true 
    },
  },
  {
    path:'/user',
    component:()=>import ('@/views/User'),
    meta: { 
      isshowtanbar: true 
    },
  },
  {
    path:'/productDetail',
    component:()=>import ('@/views/ProductDetail'),
    meta: { 
      isshowtanbar: false 
    },
  },
  
  
]
// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location) {
    return originalPush.call(this, location).catch(err => {})
};

const router = new VueRouter({
    mode:'history',
    routes
})

// 创建路由导航前置守卫
// 监控全局所有的路由导航,项目中只要有路由跳转,都会执行beforeEach中的函数,
router.beforeEach((to, from, next) => {
    // 判断一下当访问购物车页的时候, 是否用户已经登录,如果用户未登录,跳转到我的页登录
    // 如果用户已登录,执行放行
    if (to.path == '/car') {
        // 表示访问购物车页
        const token = localStorage.getItem('token'); // 返回值 字符串 或者 null
        if (token) {
            // 说明本地有token ,说明用户已经登录过
            next()
        } else {
            //  说明本地没有token,跳转到我的页完成登录
            // 先提示请先登录,然后500毫秒后跳转到我的页
            // Vue.prototype.$toast() === this.$toast()
            Vue.prototype.$toast({
                type: 'fail',
                message: '请先登录',
                duration: 1000
            })
            setTimeout(() => {
                next('/user')
            }, 1000)
        }

    } else {
        // 非购物车可以直接访问
        next()
    }
})

export default router